package org.jeecg.modules.guarantee.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.xinyuan.AES;
import org.jeecg.common.util.xinyuan.Utils;
import org.jeecg.modules.guarantee.entity.TenderGuarantee;
import org.jeecg.modules.guarantee.model.GuaranteeParam;
import org.jeecg.modules.guarantee.service.ITenderGuaranteeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags="电子保函回调接口")
@RestController
@RequestMapping("/api/web/tender")
@Slf4j
public class TenderGuaranteeWebController {
    @Autowired
    private ITenderGuaranteeService tenderApplyService;
    @Value("${tender.accessKey}")
    private String Access_key;
    @Value("${tender.secretKey}")
    private String Secret_key;
    @Value("${tender.iv}")
    private String Iv;



   @ApiOperation(value="电子保函回调接口", notes="电子保函回调接口")
   @PostMapping(value = "/guarantee")
   public JSONObject guarantee(@RequestBody GuaranteeParam guaranteeParam) {

       log.info("****************电子保函回调-请求参数==="+JSONObject.toJSON(guaranteeParam));

       if ("get_apply_guarantee_result".equals(guaranteeParam.getMethod())) { //查询保函申请结果接口
           return getApplyGuarantee(guaranteeParam);
       } else if ("feedback_apply_guarantee_result".equals(guaranteeParam.getMethod())) { //第三方回调保函接收
           return reciveThirdGuarantee(guaranteeParam);
       }
       log.info("****************保函接口调用-结束===");
       JSONObject obj=new JSONObject();
       obj.put("result","fail");
       obj.put("msg", "接口暂未开放");
       return  obj;
   }

    /**
     * 查询保函逻辑
     * @param guaranteeParam
     * @return
     */
    private JSONObject getApplyGuarantee(GuaranteeParam guaranteeParam){
        //解密
        String backdata = AES.decrypt(guaranteeParam.getData(),Secret_key,Iv);//AES解密
        JSONObject dataobj = JSONObject.parseObject(backdata);
        System.out.println("getApplyGuarantee接口data解密后dataobj=====:"+dataobj);

        //验签
        boolean checkResult = Utils.checkSign((JSONObject) JSONObject.toJSON(guaranteeParam), Secret_key);
        System.out.println("验签结果:"+checkResult);

        //验签通过，查询保函状态
        if(checkResult){
            String accept_no = dataobj.getString("accept_no");
            TenderGuarantee order = tenderApplyService.getOne(new LambdaQueryWrapper<TenderGuarantee>().eq(TenderGuarantee :: getAcceptNo,accept_no));

            if(order == null){
                JSONObject obj=new JSONObject();
                obj.put("result","fail");
                obj.put("msg", "未查询到保函订单信息");
                return  obj;
            }
            JSONObject obj=new JSONObject();
            obj.put("result","success");
            obj.put("approve_status",order.getApproveStatus());
            obj.put("accept_no",order.getAcceptNo());
            obj.put("guarantee_no",order.getGuaranteeNo());
            obj.put("guarantee_url", order.getGuaranteeUrl());

            obj.put("fee",order.getFee());
            obj.put("rate",order.getRate());
            obj.put("msg", "");

            log.info("**************getApplyGuarantee接口返回参数：" +obj.toJSONString());
            return  obj;

        }
        JSONObject obj=new JSONObject();
        obj.put("result","fail");
        obj.put("msg", "验签失败");
        return  obj;
    }


    /**
     * 保函办理结果反馈
     * @param guaranteeParam
     * @return
     */
    public JSONObject reciveThirdGuarantee(GuaranteeParam guaranteeParam){
        //解密
        String backdata = AES.decrypt(guaranteeParam.getData(),Secret_key,Iv);//AES解密
        JSONObject dataobj = JSONObject.parseObject(backdata);
        System.out.println("reciveThirdGuarantee接口data解密后dataobj=====:"+dataobj);

        //验签
        boolean checkResult = Utils.checkSign((JSONObject) JSONObject.toJSON(guaranteeParam), Secret_key);
        System.out.println("验签结果:"+checkResult);

        //验签通过，查询保函状态
        if(checkResult){
            String accept_no = dataobj.getString("accept_no");
            TenderGuarantee order = tenderApplyService.getOne(new LambdaQueryWrapper<TenderGuarantee>().eq(TenderGuarantee :: getAcceptNo,accept_no));

            if(order == null){
                JSONObject obj=new JSONObject();
                obj.put("result","fail");
                obj.put("msg", "未查询到保函订单信息");
                return  obj;
            }
            order.setApproveStatus(dataobj.getString("approve_status"));
            order.setGuaranteeNo(dataobj.getString("guarantee_no"));
            order.setGuaranteeUrl(dataobj.getString("guarantee_url"));
            order.setMerchantName(dataobj.getString("merchant_name"));
            order.setFee(dataobj.getString("fee"));
            order.setRate(dataobj.getString("rate"));
            order.setError(dataobj.getString("error"));
            order.setApproveStatus(dataobj.getString("approve_status"));


            tenderApplyService.updateById(order);
            JSONObject obj=new JSONObject();
            obj.put("result","success");
            obj.put("msg", "成功");

            log.info("**************reciveThirdGuarantee接口返回参数：" +obj.toJSONString());
            return  obj;

        }
        JSONObject obj=new JSONObject();
        obj.put("result","fail");
        obj.put("msg", "验签失败");
        return  obj;
    }

}
